package com.syni.mdd.yhd.common.all.listen.groupBuy;

import com.alibaba.fastjson.JSON;
import com.syni.mdd.sjb.common.component.utils.common.utils.BeanUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.DateTimeUtils;
import com.syni.mdd.yhd.common.all.constants.AuroraPushCode;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.entity.*;
import com.syni.mdd.yhd.common.all.entity.user.BmsUser;
import com.syni.mdd.yhd.common.all.service.*;
import com.syni.mdd.yhd.common.all.service.activity.BmsDrOrderLogService;
import com.syni.mdd.yhd.common.all.service.groupBuy.BmsDxSaleService;
import com.syni.mdd.yhd.common.all.service.groupBuy.BmsUserBargainService;
import com.syni.mdd.yhd.common.all.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @className OrderListener
 * @description TOO
 * @Author cfx
 * @DATE 2019/8/8 15:46
 * @VERSION 1.0
 **/
@Component
public class GroupBuyUseListener implements ApplicationListener<GroupBuyEvent> {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    BmsDxNewsService bmsDxNewsService;

    @Autowired
    BmsUserBusinessService bmsUserBusinessService;

    @Autowired
    BmsBusinessService bmsBusinessService;

    @Autowired
    BmsUserVideoDkService bmsUserVideoDkService;

    @Autowired
    BmsCommonService bmsCommonService;

    @Autowired
    BmsDxGroupBuyUseService bmsDxGroupBuyUseService;

    @Autowired
    BmsDxOrderService bmsDxOrderService;

    @Autowired
    BmsDrOrderLogService bmsDrOrderLogService;

    @Autowired
    BmsUserBusinessAuthService bmsUserBusinessAuthService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    BmsBusinessVerRecordService bmsBusinessVerRecordService;

    @Autowired
    BmsUserBargainService bmsUserBargainService;

    @Autowired
    BmsDxSaleService bmsDxSaleService;

    @Override
    @Async
    public void onApplicationEvent(GroupBuyEvent groupBuyEvent) {
        log.info("......................团购券核销...................");
        BmsDxOrder bmsDxOrder = groupBuyEvent.getBmsDxOrder();
        BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
        Optional<BmsBusiness> bmsBusinessOptional = bmsBusinessService.getBaseDao().findById(bmsDxGroupBuy.getBusinessId());
        if(!bmsBusinessOptional.isPresent()){
            return;
        }
        BmsBusiness business = bmsBusinessOptional.get();
        List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = groupBuyEvent.getBmsDxGroupBuyUse();
        BmsDxNews bmsDxNews = new BmsDxNews();
        bmsDxNews.setIsDelete(Constants.COMMON_FLAG_FALSE_INT);
        BmsDxNews userNew = new BmsDxNews();
        BeanUtils.copyProperties(bmsDxNews,userNew);
        if(bmsDxGroupBuyUses.size() > 0){
            //发送给商家(需要判断是否是店员核销)
            BmsDxGroupBuyUse bmsDxGroupBuyUse = bmsDxGroupBuyUses.get(0);
            bmsDxNews.setBmsBusinessId(bmsDxGroupBuy.getBusinessId());
            bmsDxNews.setOpUserId(bmsDxGroupBuyUse.getUseManId());
            bmsDxNews.setBmsOrderId(bmsDxGroupBuyUse.getOrderId());
            bmsDxNews.setBmsGroupBuyUseId(bmsDxGroupBuyUse.getId());
            bmsDxNews.setParentType(Constants.PARENTTYPT_CON);
            Map<String,Object> businessDataMap = new HashMap<>();
            bmsDxNews.setOriginRole(Constants.BUSINESS_ROLE_ID);
            if(bmsDxGroupBuyUse.getUseManRole() == Constants.BUSINESS_ROLE_ID){
                businessDataMap.put("groupName",bmsDxGroupBuy.getGroupName());
                businessDataMap.put("verNum",bmsDxGroupBuyUses.size());
                bmsDxNews.setContent(JSON.toJSONString(businessDataMap));
                bmsDxNews.setChildType(Constants.PARENTTYPT_CON_BUS_ADMIN_GROUP_BUY_USE);
                bmsDxNewsService.save(bmsDxNews);
                String alert = String.format(AuroraPushCode.pushTemplateMap.get(AuroraPushCode.BUSINESS_ADMIN_VER_GROUP_USE).getAlert(),bmsDxGroupBuy.getGroupName());
                BmsCommonService.pushToFront(bmsDxNews,AuroraPushCode.BUSINESS_ADMIN_VER_GROUP_USE,alert);
            }
            else if(bmsDxGroupBuyUse.getUseManRole() == Constants.ASSISTANT_ROLE_ID){
                //查询店员
                List<BmsUserBusiness> bmsUserBusinesses = bmsUserBusinessService.getBaseDao().findByBmsUserIdAndBmsBusinessId(bmsDxGroupBuyUse.getUseManId(),bmsDxGroupBuy.getBusinessId());
                if(bmsUserBusinesses.size() > 0){
                    bmsDxNews.setTitile(bmsUserBusinesses.get(0).getNameInStore());
                }
                businessDataMap.put("assistantName",bmsDxNews.getTitile());
                businessDataMap.put("groupName",bmsDxGroupBuy.getGroupName());
                businessDataMap.put("verNum",bmsDxGroupBuyUses.size());
                bmsDxNews.setContent(JSON.toJSONString(businessDataMap));
                bmsDxNews.setChildType(Constants.PARENTTYPT_CON_BUSINESS_GROUP_BUY_USE);
                bmsDxNewsService.save(bmsDxNews);
                String alert = String.format(AuroraPushCode.pushTemplateMap.get(AuroraPushCode.BUSINESS_VER_GROUP_USE).getAlert(),bmsDxNews.getTitile(),bmsDxGroupBuy.getGroupName());
                BmsCommonService.pushToFront(bmsDxNews,AuroraPushCode.BUSINESS_VER_GROUP_USE,alert);
            }
            //发送给用户
            userNew.setBmsBusinessId(bmsDxGroupBuy.getBusinessId());
            userNew.setBmsUserId(bmsDxGroupBuyUse.getUserId());
            userNew.setOpUserId(bmsDxGroupBuyUse.getUserId());
            userNew.setBmsOrderId(bmsDxGroupBuyUse.getOrderId());
            userNew.setBmsGroupBuyUseId(bmsDxGroupBuyUse.getId());
            userNew.setParentType(Constants.PARENTTYPT_CON);
            userNew.setChildType(Constants.PARENTTYPT_CON_GROUP_BUY_USE);
            userNew.setTitile(business.getVendorName());
            Map<String,Object> userDataMap = new HashMap<>();
            userDataMap.put("useNum",bmsDxGroupBuyUses.size());
            userDataMap.put("groupName",bmsDxGroupBuy.getGroupName());
            userNew.setContent(JSON.toJSONString(userDataMap));
            //userNew.setFromOrigin(Constants.USER_CLIENT);
            userNew.setOriginRole(Constants.GENERAL_USER_ROLE_ID);
            bmsDxNewsService.save(userNew);
            String alert = String.format(AuroraPushCode.pushTemplateMap.get(AuroraPushCode.USER_USE_GROUP_BUY).getAlert(),bmsDxGroupBuyUses.size(),business.getVendorName(),bmsDxGroupBuy.getGroupName());
            BmsCommonService.pushToFront(userNew,AuroraPushCode.USER_USE_GROUP_BUY,alert);
            //短信发送
            sendGroupBuyUseSms(bmsDxGroupBuy,bmsDxGroupBuyUse,business,bmsDxGroupBuyUses.size());
            //统计返现活动
            bmsDxGroupBuyUseService.countBackCard(bmsDxGroupBuyUse);
            //同步核销数据
            bmsBusinessVerRecordService.addBuyVerRecord(bmsDxGroupBuyUses,business.getId());
            //如果是砍价团购
            bmsUserBargainService.verBmsDxGroupBuy(bmsDxGroupBuyUses.get(0).getOrderId());
            //推荐团购的话，处理逻辑
            bmsDxSaleService.postHandGroupBuyCountRecommend(bmsDxOrder);
        }
    }

    /**
     * @Description 发送购买短信
     * @Author: cfx
     * @Date: 2019/8/28
     */
    public void sendGroupBuyUseSms(BmsDxGroupBuy bmsDxGroupBuy,BmsDxGroupBuyUse bmsDxGroupBuyUse,BmsBusiness bmsBusiness,Integer num){
        final String templateIds = "groupBuyUse.templateId";
        BmsUser bmsUser = TokenManager.getUser(bmsDxGroupBuyUse.getUserId());
        if(bmsUser != null && StringUtils.isNotBlank(bmsUser.getPhone())){
            String phone = bmsUser.getPhone();
            String[] params = {
                    DateTimeUtils.converDateToString(bmsDxGroupBuyUse.getUseTime(), DateTimeUtils.DATE_PATTERN_DAY_06),
                    num.toString(),
                    bmsBusiness.getVendorName(),
                    bmsDxGroupBuy.getGroupName()
            };
            if(BmsCommonService.checkRunProfile(BmsCommonService.RUN_PRO)){
                SmsUtils.send(phone,templateIds,params);
            }
        }
    }
}
